let token = getToken();
let user = JSON.parse(window.localStorage.getItem("userInfo"));
let url;
let currentNodeName = null;
var res = playGet(`/v1/api/users/queue/${user.id}`);
const maxPnum = res.data.nummber;
if (res.code == 200) {
  const {
    data: { id },
  } = res;
  const promiseList = [];
  for (let i = 1; i < 4; i++) {
    const promiseFunc = new Promise((resolve) => {
      resolve(
        $.ajax({
          url: `${server}/v1/api/setting/tj/queue/zhu/${id}/${i}`,
          // url: `http://47.111.243.54:504/v1/api/setting/tj/queue/zhu/1/${i}`, // 有数据
        })
      );
    });
    promiseList.push(promiseFunc);
  }

  const showCurrentUserAtTreeChart = (pnum) => {
    const otherNode = $(".other");
    for (let i = 0; i < otherNode.length; i++) {
      if (String(pnum) === otherNode.eq(i).text()) {
        otherNode.eq(i).addClass("active");
      }
    }
  };

  const setLastShowNode = (pnum) => {
    typeof pnum === "string" && (pnum = Number(pnum));
    const otherNode = $(".other-next");
    for (let i = 0; i < otherNode.length; i++) {
      const nodeVal = Number(otherNode.eq(i).text());
      if (nodeVal > pnum) {
        // otherNode.eq(i).addClass('not-show')
        otherNode.eq(i).html("");
      }
    }
  };

  const toRenderTeamList = (list) => {
    const allPnum = [];
    const teamListContainer = $("#dataList");
    const allTeamListNode = list
      .map((i) => {
        const { code, data } = i;
        if (data.length > 0) {
          const teamList = data
            .map((j, jIndex) => {
              console.log('dsad', j)
              const { id, pnum, name, mobile, userName } = j;
              allPnum.push(pnum);
              const isCurrentUser =
                id ===
                JSON.parse(localStorage.getItem("userInfo") || { id: null }).id;
              isCurrentUser && showCurrentUserAtTreeChart(pnum);
              const teamListTemplate = `
											<li class="${isCurrentUser ? "is-current-user" : ""}">
												<img src="phoneContent/img/headImg.png"/>
												<div class="fr">
													<p class="t_name">账号:${userName}</p>
                          <p class="t_name">手机号:${mobile}</p>
                          <p class="t_id">所占点位：${pnum}</p>
													<p class="t_id">ID：${id}</p>
												</div>
											
											</li>
											`;
              return teamListTemplate;
            })
            .join("");
          return `<div class="team-list-div">${teamList}</div>`;
        } else {
          return ''
        }

      })
      .join("");
    setLastShowNode(allPnum.length > 0 ? allPnum.reduce((a, b) => (a > b ? a : b)) : 0);
    teamListContainer.append(allTeamListNode);
  };

  const getTreeNameData = (data) => {
    const levelTwoObj = data.children && Array.isArray(data.children) ? data.children[0] : { name: '' };
    const levelThreeObj = levelTwoObj.children && Array.isArray(levelTwoObj.children) ? levelTwoObj.children[0] : { name: '' };
    const levelFourObjs =
      levelThreeObj.children && Array.isArray(levelThreeObj.children)
        ? levelThreeObj.children
        : [];
    const levelFiveObjs = [];
    levelFourObjs.forEach((item) => {
      if (Array.isArray(item.children)) {
        item.children.forEach((t) => {
          levelFiveObjs.push(t)
        })
      }
    })

    if (data.id != user.id) {
      data.name = '';

      if (levelTwoObj.id != user.id) {
        levelTwoObj.name = '';

        if (levelThreeObj.id != user.id) {
          levelThreeObj.name = '';

          levelFiveObjs.forEach((item) => {
            if (item.id != user.id) {
              item.llname = item.name;
              item.name = '';
            } else {
              currentNodeName = item.name;
            }
          });

          levelFourObjs.forEach((item) => {
            if (item.id != user.id) {
              item.name = '';
            } else {
              currentNodeName = item.name;
              levelFiveObjs.forEach((em) => {
                if (em.inUserId == item.id) {
                  em.name = em.llname;
                }
              });
            }
          });

        }

      }

    }



    // 第一层和第二层只有一个节点
    const levelOneName = data.name;
    const levelTwoName = levelTwoObj.name;
    const levelThreeNames = levelThreeObj.name;
    const levelFourNames = levelFourObjs.map((i) => i.name);
    const levelFiveNames = levelFiveObjs.map((i) => i.name);

    return {
      levelOneName,
      levelTwoName,
      levelThreeNames,
      levelFourNames,
      levelFiveNames,
    };
  };

  const getTreeData = (data) => {
    console.log('data', data)
    let isCurrentUser = false
    let right = '>'
    const teamListTemplate = `
      <li class="${isCurrentUser ? "is-current-user" : "", 'card-right'}">
        <img src="phoneContent/img/headImg.png"/>
        <div class="fr">
          <p class="t_name">账号:23423</p>
          <p class="t_name">手机号:2434</p>
        </div>
        <div class="to-right">${right}</div>
      </li>
      `;
    $("#treeDataList").html(teamListTemplate)
  }

  const toRenderTreeNode = (resData) => {
    const treeContainer = $("#tree_chart_container");
    let { code, data } = resData;
    // if (!data) data = mockData
    // if (!data) {
    //   treeContainer.show();
    //   treeContainer.children().not(".other-next-container").hide();
    //   treeContainer
    //     .children(".other-next-container")
    //     .eq(0)
    //     .addClass("not-top-line");
    //   return;
    // }
    if (code === 200 && data) {
      treeContainer.show();
      const namesObj = getTreeNameData(data);
      const {
        levelOneName,
        levelTwoName,
        levelThreeNames,
        levelFourNames,
        levelFiveNames,
      } = namesObj;
      $(".level-one").html(levelOneName);
      $(".level-two").html(levelTwoName);
      $(".level-three").html(levelThreeNames);
      const levelFourDomList = $(".level-four").children();
      for (let i = 0; i < levelFourDomList.length; i++) {
        if (levelFourNames[i] == currentNodeName) {
          levelFourDomList.eq(i).addClass('active');
        }
        levelFourDomList.eq(i).html(levelFourNames[i]);
      }

      const levelFiveDomeList = $(".level-five").children();
      for (let i = 0; i < levelFiveDomeList.length; i++) {
        if (levelFiveNames[i] == currentNodeName) {
          levelFiveDomeList.eq(i).addClass('active');
        }
        levelFiveDomeList.eq(i).html(levelFiveNames[i]);
      }
      // 树
      getTreeData(data)
    }
  };

  function getNodeData() {
    new Promise((resolve) =>
      resolve(
        $.ajax({
          // url: `${server}/v1/api/setting/tj/user/queue/${user.id}/${id}`,
          url: `${server}/v1/api/setting/tj/queue/${id}`,
          // url: `${server}/v1/api/setting/tu/user/${user.id}`,
          // url: `https://sdqn5b.cn:449/v1/api/setting/tj/queue/827246627533094921?`,
        })
      )
    )
      .then(toRenderTreeNode)
      .then(() => {
        Promise.allSettled(promiseList)
          .then((res) => {
            const teamListData = [];
            res.forEach((i) => {
              const { status, value } = i;
              if (status !== "fulfilled") return console.log("数据获取失败");
              teamListData.push(value);
            });
            return teamListData;
          })
          // .then(toRenderTreeNextNodeList)
          .then(toRenderTeamList)
          .catch((err) => console.log(err));
      });
  }

  getNodeData();

  // function getNodeLocation(id) {
  //   $.ajax({
  //     url: `${server}/v1/api/setting/tu/user/${id}`,
  //     success(res) {
  //       const { data } = res;
  //       const { number, hz, tree } = data;
  //     }
  //   })
  // }

  // getNodeLocation(user.id)
} else {
  mui.alert(res.msg);
}


